import itemTpl from "./tpl/item.tpl";
import wrapperTpl from "./tpl/index.tpl";
import './index.scss';

import { tplReplace, scrollToTop } from "../../libs/utils";


export default {
    name: 'NavBar',
    _curInx: 0,
    tpl (data) {
        let itemList = '';

        // 先用数据来渲染出list
        data.map(({ type, title }, index) => {
            itemList += tplReplace(itemTpl, {
                isCurrent: !index ? 'current' : '',
                title,
                type
            })
        });

        // 把list和宽度数据替换到模版中
        return tplReplace(wrapperTpl, {
            itemList,
            wrapperW: .6 * data.length
        })
    },

    // 绑定点击分类触发的事件
    bindEvent (setType) {
        const oNavBar = document.querySelector('.nav');
        const oNavItems = document.querySelectorAll('.item');

        oNavBar.addEventListener('click', this._setNav.bind(this, oNavItems, setType), false);
    },

    _setNav (items, setType) {
        const tar = arguments[2].target;
        const className = tar.className.trim();

        if (className === "item") {
            const type = tar.dataset.type;
            // 把点击的分类传回到页面操作
            setType(type);
            // 回到顶部
            scrollToTop();
            // 高亮当前点击项
            items[this._curInx].className = 'item';
            this._curInx = [].indexOf.call(items, tar);
            items[this._curInx].className += ' current';
        } 
    }
}